/*
 * main.c
 *
 *  Created on: Dec 10, 2011
 *      Author: Michael Anderson
 *      Part of Team 955 Battery Cart project
 *      compiled on Eclipse with Arduino libraries and avr-gcc
 */

#include "main.h"

void setup() {
    Serial.begin(SERIAL_SPEED);

    //Initialize da pins
    initPins();

    for (uint8_t i = 0; i < NUM_DISPLAYS; i++) {
        displays[i] = new Display(i, PINS_DISPLAY[i][PIN_TYPE_DISPLAY_RS], PINS_DISPLAY[i][PIN_TYPE_DISPLAY_RW],
                PINS_DISPLAY[i][PIN_TYPE_DISPLAY_ENABLE], PINS_DISPLAY[i][PIN_TYPE_DISPLAY_D0],
                PINS_DISPLAY[i][PIN_TYPE_DISPLAY_D1], PINS_DISPLAY[i][PIN_TYPE_DISPLAY_D2],
                PINS_DISPLAY[i][PIN_TYPE_DISPLAY_D3], PINS_DISPLAY[i][PIN_TYPE_DISPLAY_D4],
                PINS_DISPLAY[i][PIN_TYPE_DISPLAY_D5], PINS_DISPLAY[i][PIN_TYPE_DISPLAY_D6],
                PINS_DISPLAY[i][PIN_TYPE_DISPLAY_D7]);
        //displaysInitialized = true;
    }

    //Setup the logger so we can give it to the objects
    eManager = new EventManager();
    keypd = new MyKeypad();

    //Set up all of our batteries, chargers, and conditioners with the proper parameters
    for (uint8_t i = 0; i < NUM_CHARGING_CIRCUITS; i++) {
        batteries[i] = new Battery(i);
        chargers[i] = new Charger(*batteries[i], PINS_CHARGER[i], *eManager);
    }

    for (uint8_t i = 0; i < NUM_CONDITIONERS; i++) {
        conditioners[i] = new Conditioner(i, *eManager);
    }

    menu = new Menu(displays, *keypd, *eManager, batteries, chargers, conditioners);

    //msgCount = 0;
}

void loop() {
    menu->run();
}

void initPins() {
#if FASTADC
    // set prescale to 32
    sbi(ADCSRA,ADPS2) ;
    cbi(ADCSRA,ADPS1) ;
    sbi(ADCSRA,ADPS0) ;
#endif

    uint8_t i;
    for (i = 0; i < NUM_CHARGING_CIRCUITS; i++) {
        pinMode(PINS_INVERTER[i], OUTPUT);
        digitalWrite(PINS_INVERTER[i], LOW);
        pinMode(PINS_CHARGER[i], OUTPUT);
        digitalWrite(PINS_CHARGER[i], LOW);
    }

    for (i = 0; i < NUM_CONDITIONERS; i++) {
        for (uint8_t j = 0; j < NUM_LOADS; j++) {
            pinMode(PINS_LOADS[i][j], OUTPUT);
            digitalWrite(PINS_LOADS[i][j], LOW);
        }
    }

    analogReference(DEFAULT);
}
